package com.ruoyi.tcustomer.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    public static String toMD5(String original) {
        try {
            // 创建一个MessageDigest实例，指定使用MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用指定的字节数组更新摘要
            md.update(original.getBytes());
            // 计算摘要
            byte[] digest = md.digest();
            // 将摘要转换为16进制字符串
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 将字节数组转换为16进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static boolean verifyMD5(String original, String storedHash) {
        String calculatedHash = toMD5(original);
        return calculatedHash.equals(storedHash);
    }

}
